<?php

namespace Admin\Controller;

class MsgController extends CommonController
{
    // 站内信列表
    public function lists()
    {
        $sort = ' id desc';
        $key  = I('request.key', '', 'trim');

        if ($key) {
            $key_type = I('request.key_type', 0, 'intval');
            if ($key_type == '1') {
                $map['content'] = array('like', '%' . $key . '%');
            }
            if ($key_type == '2') {
                $map['uid'] = intval($key);
            }
        }

        $list = D('Msg')->get_list($map, true, $sort, 10);
        $this->assign('lists', $list);

        $this->display();
    }

    // 添加站内信
    public function add()
    {
        if (IS_POST) {
            $msg = D("Msg");
            if (!$mod = $msg->create()) {
                $this->error($msg->getError());
            } else {
                $mod->uid = session('ytata.uid');
                if ($mod->receiver == '2') {  // 指定会员
                    $uname           = explode("\r\n", $mod->receiver_by);
                    $map['username'] = array('IN', $uname);
                    $uids            = M('User')->where($map)->getField('uid', true);
                    $uids            = implode(",", $uids);

                    $mod->receiver_by = $uids;
                }

                $msgid = $msg->add();

                $this->success('保存完成', RU('msg/lists'));
            }
        } else {
            $this->display();
        }
    }

    // 编辑站内信
    public function edit()
    {
        if (IS_POST) {
            $data = D("Msg");
            if (!$array = $data->create()) {
                $this->error($data->getError());
            } else {
                $data->save();
                $this->success('保存完成');
            }
        } else {
            $id = I('get.id', '', 'intval');
            if ($id) {
                $data      = M("Msg");
                $map['id'] = $id;
                $show      = $data->where($map)->find();
                $this->assign('show', $show);
                $this->display();
            } else {
                $this->error('非法请求');
            }
        }
    }

    // 删除站内信
    public function delete()
    {
        $ids = I('request.id');
        $ids = is_array($ids) ? implode(",", $ids) : $ids;
        if ($ids && preg_match("/^(\d{1,10},)*(\d{1,10})$/", $ids)) {

            $map['msg_id'] = array('IN', $ids);
            $map['read']   = 0;
            M("UserMsg")->where($map)->delete();
            $s = M("Msg")->delete($ids);
            $this->success("成功删除{$s}条数据");
        } else {
            $this->error('请选择要删除的信息！');
        }
    }
}